package FanShe5;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestDemo {
    public static void main(String[] args) throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        //测试没有反射
//        Teacher teacher = new Teacher();
//        String typeInstanceof = TestDemo.getTypeInstanceof(teacher);
//        System.out.println("typeInstanceof = " + typeInstanceof);
//
//        Student student = new Student();
//        String typeInstanceof1 = TestDemo.getTypeInstanceof(student);
//        System.out.println("typeInstanceof1 = " + typeInstanceof1);


        //测试反射效果
        Teacher teacher = new Teacher();
        String type = getType(teacher);
        System.out.println("type = " + type);


    }
    /**
     * 不使用反射，常规用法
     */
    public static String getTypeInstanceof(Object obj)
    {
        if(obj instanceof Student)//true
        {
            Student student = (Student) obj;
            String userType = student.getUserType("王小明");
            return userType;
        }
        if(obj instanceof Teacher)//true
        {
            Teacher teacher = (Teacher) obj;
            String userType = teacher.getUserType("张老师");
            return userType;
        }

        return null;
    }

    /**
     * 使用反射实现
     */
    public  static String getType(Object obj) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<?> aClass = obj.getClass();//获取反射对象
        Object instance = aClass.newInstance();//通过发射对象实例化类对象
        Method getUserType = aClass.getMethod("getUserType", String.class);
        String invoke = (String)getUserType.invoke(instance, "王明");
        return invoke;

    }
}
